package org.codehaus.activemq.ra;

import javax.resource.ResourceException;
import javax.resource.spi.ConnectionEvent;
import javax.resource.spi.ConnectionEventListener;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
import javax.security.auth.Subject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DefaultConnectionManager
  implements ConnectionManager, ConnectionEventListener
{
  private static final Log log = LogFactory.getLog(DefaultConnectionManager.class);

  public Object allocateConnection(ManagedConnectionFactory connectionFactory, ConnectionRequestInfo info)
    throws ResourceException
  {
    Subject subject = null;
    ManagedConnection connection = connectionFactory.createManagedConnection(subject, info);
    connection.addConnectionEventListener(this);
    return connection.getConnection(subject, info);
  }

  public void connectionClosed(ConnectionEvent event)
  {
    try
    {
      ((ManagedConnection)event.getSource()).cleanup();
    }
    catch (ResourceException e) {
      log.warn("Error occured during the cleanup of a managed connection: ", e);
    }
    try {
      ((ManagedConnection)event.getSource()).destroy();
    }
    catch (ResourceException e) {
      log.warn("Error occured during the destruction of a managed connection: ", e);
    }
  }

  public void localTransactionStarted(ConnectionEvent event)
  {
  }

  public void localTransactionCommitted(ConnectionEvent event)
  {
  }

  public void localTransactionRolledback(ConnectionEvent event)
  {
  }

  public void connectionErrorOccurred(ConnectionEvent event)
  {
    log.warn("Managed connection experiened an error: ", event.getException());
    try {
      ((ManagedConnection)event.getSource()).cleanup();
    }
    catch (ResourceException e) {
      log.warn("Error occured during the cleanup of a managed connection: ", e);
    }
    try {
      ((ManagedConnection)event.getSource()).destroy();
    }
    catch (ResourceException e) {
      log.warn("Error occured during the destruction of a managed connection: ", e);
    }
  }
}